package com.yilin.tms.order.service.clearing.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yilin.commons.exception.BusinessException;
import com.yilin.commons.util.ArrayUtil;
import com.yilin.commons.util.DateTimeUtil;
import com.yilin.commons.util.MathUtil;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.PageData;
import com.yilin.tms.core.commons.base.BaseEntity;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.QueryUtil;
import com.yilin.tms.core.entity.order.clearing.ClearingDetail;
import com.yilin.tms.core.entity.order.clearing.GatherRecord;
import com.yilin.tms.core.entity.order.goods.GoodsOrder;
import com.yilin.tms.core.entity.order.rob.RobOrder;
import com.yilin.tms.core.entity.order.transit.TransitOrder;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.remote.IUserRemote;
import com.yilin.tms.order.mapper.clearing.GatherRecordMapper;
import com.yilin.tms.order.mapper.goods.GoodsOrderMapper;
import com.yilin.tms.order.mapper.rob.RobOrderMapper;
import com.yilin.tms.order.mapper.transit.TransitOrderMapper;
import com.yilin.tms.order.service.clearing.IClearingService;
import com.yilin.tms.order.service.clearing.IGatherService;
import com.yilin.tms.order.service.payment.ICalculationService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackOn = Exception.class)
public class GatherService extends ServiceImpl<GatherRecordMapper, GatherRecord> implements IGatherService {
    Logger logger = LoggerFactory.getLogger(GatherService.class);

    @Resource
    private RobOrderMapper robOrderMapper;
    @Resource
    private GoodsOrderMapper goodsOrderMapper;
    @Resource
    private TransitOrderMapper transitOrderMapper;
    @Resource
    private GatherRecordMapper gatherRecordMapper;
    @Resource
    private IClearingService clearingService;
    @Resource
    private ICalculationService calculationService;

    @Override
    public PageData<GatherRecord> getGatherRecordPage(Account loginUser, GatherRecord query, Integer page, Integer limit) {
        QueryWrapper<GatherRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plat_id", loginUser.getOrganizeId());
        return gatherRecordMapper.selectPage(new PageData<>(page, limit), QueryUtil.andQueryWrapper(queryWrapper, query));
    }

    /**
     * 作废汇总
     */
    @Override
    public void scrapGatherRecord(String gatherRecordId, String scrapReason,Account loginUser) {
        GatherRecord gatherRecord = gatherRecordMapper.selectById(gatherRecordId);
        if (gatherRecord == null) {
            throw new BusinessException("不存在该汇总");
        }
        if (gatherRecord.getGatherStatus() == GatherRecord.GatherStatus.confirmed) {
            throw new BusinessException("该汇总已完成不可作废！");
        }
        List<ClearingDetail> list = clearingService.getClearingListByGatherId(gatherRecordId);
        for (ClearingDetail clearingDetail : list) {
            if (clearingDetail.getClearingStatus()== ClearingDetail.ClearingStatus.success){
                throw new BusinessException("该汇总存在清算完成订单不可作废！");
            }
        }
        if (StringUtil.isEmpty(scrapReason)) {
            gatherRecord.setScrapReason(scrapReason);
        }
        gatherRecord.setGatherStatus(GatherRecord.GatherStatus.scrap);
        gatherRecord.setScrapTime(new Date());
        gatherRecord.setScrapAccountName(loginUser.getName());
        gatherRecord.setScrapAccountId(loginUser.getId());
        gatherRecordMapper.updateById(gatherRecord);
    }

    /**
     * 开始汇总
     */
    @Override
    public GatherRecord createGatherRecord(Account loginUser, List<TransitOrder> transitOrderList) {

        TransitOrder firstOrder = transitOrderList.get(0);
        checkGatherRecord(firstOrder, transitOrderList);
        //-开始创建
        GatherRecord gatherRecord = new GatherRecord();
        gatherRecord.setGatherRecordNo(DateTimeUtil.dateNo("GR"));
        gatherRecord.setTransitOrderIds(ArrayUtil.fieldAddStrJoin(transitOrderList, BaseEntity::getId));
        gatherRecord.setTransitOrderNos(ArrayUtil.fieldAddStrJoin(transitOrderList, TransitOrder::getTransportNo));
        gatherRecord.setIncludedTax(firstOrder.getIncludedTax());
        gatherRecord.setMatchmaking(firstOrder.getMatching());
        gatherRecord.setGatherStatus(GatherRecord.GatherStatus.create);
        //平台信息
//        gatherRecord.setZonePlatId(firstOrder.getZonePlatId());
//        gatherRecord.setPlatId(firstOrder.getPlatId());
//        gatherRecord.setZonePlatName(firstOrder.getZonePlatName());
//        gatherRecord.setPlatName(firstOrder.getPlatName());
        //-货主信息
        gatherRecord.setShipperOrganizeId(firstOrder.getShipperOrganizeId());
        gatherRecord.setShipperOrganizeName(firstOrder.getShipperOrganizeName());
        //-车主信息
        gatherRecord.setRobOrganizeId(firstOrder.getRobOrganizeId());
        gatherRecord.setRobOrganizeName(firstOrder.getRobOrganizeName());
        //-赋值默认费率
        GoodsOrder goodsOrder = goodsOrderMapper.selectById(firstOrder.getGoodsOrderId());
        RobOrder robOrder = robOrderMapper.selectById(firstOrder.getRobOrderId());
        gatherRecord.setShipperTaxRate(goodsOrder.getShipperTaxRate());
        gatherRecord.setShipperFeeRate(goodsOrder.getShipperFeeRate());
        gatherRecord.setInsuranceRate(goodsOrder.getInsuranceRate());
        gatherRecord.setTruckerFeeRate(robOrder.getTruckerFeeRate());
        gatherRecord.setAddedTaxRate(robOrder.getAddedTaxRate());
        gatherRecord.setCityTaxRate(robOrder.getCityTaxRate());
        gatherRecord.setLocalEduTaxRate(robOrder.getLocalEduTaxRate());
        gatherRecord.setEduAddTaxRate(robOrder.getEduAddTaxRate());
        gatherRecord.setIncomeTaxRate(robOrder.getIncomeTaxRate());
        //固定汇总累加
        gatherRecord.setTotalInsuranceCost(ArrayUtil.numListAdd(transitOrderList, TransitOrder::getInsuredCost));
        gatherRecord.setGatherAdditionalCost(ArrayUtil.numListAdd(transitOrderList, TransitOrder::getAdditionalCost));
        gatherRecord.setGatherDiffIndemnityCost(ArrayUtil.numListAdd(transitOrderList, TransitOrder::getGatherTransportCost));
        //-谁发起的汇总，锁定谁
        gatherRecord.setOptAccountId(loginUser.getId());
        gatherRecord.setOptAccountName(loginUser.getName());
        gatherRecord.setLockTime(new Date());
        gatherRecordMapper.insert(gatherRecord);
        return gatherRecord;
    }

    /**
     * 更新汇总
     */
    @Override
    public void updateGatherRecord(Account loginUser, GatherRecord fromRecord) {
        if (fromRecord.getGatherActualPayCost() == null) throw new BusinessException("汇总金额不能为空！");
        GatherRecord gatherRecord = gatherRecordMapper.selectById(fromRecord.getId());
        if (gatherRecord == null) throw new BusinessException("汇总记录不存在");
        if (gatherRecord.getGatherStatus() == GatherRecord.GatherStatus.confirmed)
            throw new BusinessException("汇总记录已确认");
        if (gatherRecord.getGatherStatus() == GatherRecord.GatherStatus.scrap)
            throw new BusinessException("汇总记录已作废");
        if (gatherRecord.getOptAccountId() == null) throw new BusinessException("请先锁定记录");
        if (!gatherRecord.getOptAccountId().equals(loginUser.getId()))
            throw new BusinessException("该记录正在被其他人操作");
        //更新汇总费率
        gatherRecord.setInsuranceRate(fromRecord.getInsuranceRate());
        gatherRecord.setGatherActualPayCost(fromRecord.getGatherActualPayCost());

        gatherRecord.setShipperTaxRate(fromRecord.getShipperTaxRate());//*
        gatherRecord.setShipperFeeRate(fromRecord.getShipperFeeRate());//*
        gatherRecord.setTruckerFeeRate(fromRecord.getTruckerFeeRate());//*
        gatherRecord.setAddedTaxRate(fromRecord.getAddedTaxRate());//*
        gatherRecord.setCityTaxRate(fromRecord.getCityTaxRate());//*
        gatherRecord.setLocalEduTaxRate(fromRecord.getLocalEduTaxRate());//*
        gatherRecord.setEduAddTaxRate(fromRecord.getEduAddTaxRate());//*
        gatherRecord.setIncomeTaxRate(fromRecord.getIncomeTaxRate());//*

        gatherRecord.setGatherShipperTaxCost(fromRecord.getGatherShipperTaxCost());//*
        gatherRecord.setGatherShipperFeeCost(fromRecord.getGatherShipperFeeCost());//*
        gatherRecord.setGatherTruckerFeeCost(fromRecord.getGatherTruckerFeeCost());//*
        gatherRecord.setGatherAddedTaxCost(fromRecord.getGatherAddedTaxCost());//*
        gatherRecord.setGatherCityTaxCost(fromRecord.getGatherCityTaxCost());//*
        gatherRecord.setGatherLocalEduTaxCost(fromRecord.getGatherLocalEduTaxCost());//*
        gatherRecord.setGatherEduAddTaxCost(fromRecord.getGatherEduAddTaxCost());//*
        gatherRecord.setGatherIncomeTaxCost(fromRecord.getGatherIncomeTaxCost());//*
        //更新汇总固定金额
        gatherRecord.setTotalInsuranceCost(fromRecord.getTotalInsuranceCost());
        gatherRecord.setGatherAdditionalCost(fromRecord.getGatherAdditionalCost());
        gatherRecord.setGatherDiffIndemnityCost(fromRecord.getGatherDiffIndemnityCost());
        gatherRecord.setGatherOilCost(fromRecord.getGatherOilCost());
        gatherRecord.setGatherEtcTollCost(fromRecord.getGatherEtcTollCost());

        //计算运输费(+保费+附加费)、税费
        double gatherTotalCostA,gatherTotalCost;
        if (gatherRecord.getGatherShipperFeeCost()!=null && gatherRecord.getGatherShipperFeeCost()>0){
            gatherTotalCostA = MathUtil.subtract(gatherRecord.getGatherActualPayCost() - gatherRecord.getGatherShipperFeeCost());
        }else{
            gatherTotalCostA = MathUtil.divide(gatherRecord.getGatherActualPayCost(), MathUtil.add(1D, gatherRecord.getShipperFeeRate()), 2);
        }
        if (!gatherRecord.getIncludedTax()) {
            if (gatherRecord.getGatherShipperTaxCost()!=null && gatherRecord.getGatherShipperTaxCost()>0){//
                gatherTotalCost = MathUtil.subtract(gatherTotalCostA - gatherRecord.getGatherShipperTaxCost());
                //费用》费率
                gatherRecord.setShipperTaxRate(MathUtil.divide(gatherRecord.getGatherShipperTaxCost(),gatherTotalCost,8));
            }else{
                gatherTotalCost = MathUtil.divide(gatherTotalCostA, MathUtil.add(1D, gatherRecord.getShipperTaxRate()), 2);
                //费率》费用
                gatherRecord.setGatherShipperTaxCost(MathUtil.multiply(gatherTotalCost, gatherRecord.getShipperTaxRate(),2));
            }
        } else {
            gatherTotalCost = gatherTotalCostA;
        }
        double gatherTotalTransportCost = MathUtil.subtract(gatherTotalCost, gatherRecord.getTotalInsuranceCost(), gatherRecord.getGatherAdditionalCost());
        gatherRecord.setGatherTotalTransportCost(gatherTotalTransportCost);
        //费用生产完成，准备计算服务费
        if (gatherRecord.getGatherShipperFeeCost()!=null && gatherRecord.getGatherShipperFeeCost()>0){//费用》费率
            gatherRecord.setShipperFeeRate(MathUtil.divide(gatherRecord.getGatherShipperFeeCost(),gatherTotalTransportCost,8));
        }else{//费率》费用
            gatherRecord.setGatherShipperFeeCost(MathUtil.multiply(gatherTotalTransportCost, gatherRecord.getShipperFeeRate(), 2));
        }
        //更新司机费用明细
        if (gatherRecord.getGatherTruckerFeeCost()!=null&& gatherRecord.getGatherTruckerFeeCost()>0){//费用》费率
            gatherRecord.setTruckerFeeRate(MathUtil.divide(gatherRecord.getGatherTruckerFeeCost(), gatherTotalTransportCost,8));
        }else{//费率》费用
            gatherRecord.setGatherTruckerFeeCost(MathUtil.multiply(gatherTotalTransportCost, gatherRecord.getTruckerFeeRate(),2));
        }

        //增值税
        if (gatherRecord.getGatherAddedTaxCost()!=null&& gatherRecord.getGatherAddedTaxCost()>0) {//费用》费率
            gatherRecord.setAddedTaxRate(MathUtil.divide(gatherRecord.getGatherAddedTaxCost(), gatherTotalTransportCost,8));
        }else{//费率》费用
            double addedTaxCost = MathUtil.multiply(gatherTotalTransportCost, gatherRecord.getAddedTaxRate(),2);
            gatherRecord.setGatherAddedTaxCost(addedTaxCost);
        }

        //基于增值税
        if (gatherRecord.getGatherAddedTaxCost()!=null && gatherRecord.getGatherAddedTaxCost()>0){
            if (gatherRecord.getGatherCityTaxCost()!=null&& gatherRecord.getGatherCityTaxCost()>0) {//费用》费率
                gatherRecord.setCityTaxRate(MathUtil.divide(gatherRecord.getGatherCityTaxCost(), gatherRecord.getGatherAddedTaxCost(),8));
            }else{//费率》费用
                double cityTaxCost = MathUtil.multiply(gatherRecord.getGatherAddedTaxCost(), gatherRecord.getCityTaxRate(),2);
                gatherRecord.setGatherCityTaxCost(cityTaxCost);
            }

            if (gatherRecord.getGatherLocalEduTaxCost()!=null&& gatherRecord.getGatherLocalEduTaxCost()>0) {//费用》费率
                gatherRecord.setLocalEduTaxRate(MathUtil.divide(gatherRecord.getGatherLocalEduTaxCost(), gatherRecord.getGatherAddedTaxCost(),8));
            }else{//费率》费用
                double localEduTaxCost = MathUtil.multiply(gatherRecord.getGatherAddedTaxCost(), gatherRecord.getLocalEduTaxRate(),2);
                gatherRecord.setGatherLocalEduTaxCost(localEduTaxCost);
            }

            if (gatherRecord.getGatherEduAddTaxCost()!=null&& gatherRecord.getGatherEduAddTaxCost()>0) {//费用》费率
                gatherRecord.setEduAddTaxRate(MathUtil.divide(gatherRecord.getGatherEduAddTaxCost(), gatherRecord.getGatherAddedTaxCost(),8));
            }else{//费率》费用
                double eduAddTaxCost = MathUtil.multiply(gatherRecord.getGatherAddedTaxCost(), gatherRecord.getEduAddTaxRate(),2);
                gatherRecord.setGatherEduAddTaxCost(eduAddTaxCost);
            }
        }

        //个所税
        if (gatherRecord.getGatherIncomeTaxCost()!=null&& gatherRecord.getGatherIncomeTaxCost()>0) {// 费用》费率
            gatherRecord.setIncomeTaxRate(MathUtil.divide(gatherRecord.getGatherIncomeTaxCost(), gatherTotalTransportCost,8));
        }else{//费率》费用
            double incomeTaxCost = MathUtil.multiply(gatherTotalTransportCost, gatherRecord.getIncomeTaxRate(),2);
            gatherRecord.setGatherIncomeTaxCost(incomeTaxCost);
        }

        gatherRecord.setGatherTruckerTaxCost(MathUtil.add(
                gatherRecord.getGatherAddedTaxCost(),
                gatherRecord.getGatherCityTaxCost(),
                gatherRecord.getGatherLocalEduTaxCost(),
                gatherRecord.getGatherEduAddTaxCost(),
                gatherRecord.getGatherIncomeTaxCost()
        ));

        double truckerActualTheoryCost = MathUtil.subtract(gatherTotalTransportCost, gatherRecord.getGatherTruckerFeeCost());
        truckerActualTheoryCost = MathUtil.subtract(truckerActualTheoryCost, gatherRecord.getGatherDiffIndemnityCost(),
                gatherRecord.getGatherOilCost(),
                gatherRecord.getGatherEtcTollCost(),
                gatherRecord.getGatherTruckerTaxCost());
        truckerActualTheoryCost = MathUtil.add(truckerActualTheoryCost, gatherRecord.getGatherAdditionalCost());
        gatherRecord.setGatherTruckerTheoryCost(MathUtil.round(truckerActualTheoryCost, 2));

        /**
         * TODO: 危险区标记 1
         * 在汇总计算司机的【提现】手续费，可能汇总出现业务问题
         * 计算司机提现手续费还有清算位置
         * */
        //用理论费用计算实际费用
        double technicalFee = calculationService.calculateTechnicalFee(truckerActualTheoryCost);
        gatherRecord.setGatherTechnicalFeeCost(technicalFee);
        gatherRecord.setGatherTruckerIncomeCost(MathUtil.round(MathUtil.subtract(truckerActualTheoryCost,technicalFee), 2));
        gatherRecord.setOptTime(new Date());
        gatherRecordMapper.updateById(gatherRecord);
    }

    /**
     * 确认汇总记录
     * 摊分费用
     * 生成清算
     */
    @Override
    public void sureGatherRecord(Account loginUser, String gatherRecordId, Boolean sureClearing) {
        GatherRecord gatherRecord = gatherRecordMapper.selectById(gatherRecordId);
        if (gatherRecord == null) throw new BusinessException("汇总记录不存在");
        if (gatherRecord.getGatherStatus() == GatherRecord.GatherStatus.scrap)
            throw new BusinessException("汇总记录已作废");
        if (gatherRecord.getGatherStatus() == GatherRecord.GatherStatus.confirmed)
            throw new BusinessException("汇总记录已确认");
        if (gatherRecord.getOptAccountId() == null) throw new BusinessException("请先锁定记录");
        if (!gatherRecord.getOptAccountId().equals(loginUser.getId()))
            throw new BusinessException("该记录正在被其他人操作");
        if (gatherRecord.getGatherActualPayCost() == null) throw new BusinessException("请先更新汇总！");
        gatherRecord.setAutoSureClearing(sureClearing);
        gatherRecord.setGatherStatus(GatherRecord.GatherStatus.deal);
        gatherRecord.setOptAccountId(loginUser.getId());
        gatherRecord.setOptAccountName(loginUser.getName());
        gatherRecordMapper.updateById(gatherRecord);
    }

    /**
     * 汇总自动确认清算
     * */
    @Override
    @Transactional(Transactional.TxType.NEVER)
    public void gatherAutoSure(){
        List<GatherRecord> autoClearingGatherList = getAutoClearingGather();
        for (GatherRecord gatherRecord : autoClearingGatherList) {
            Account loginUser = new Account();
            loginUser.setId(gatherRecord.getOptAccountId());
            loginUser.setName(gatherRecord.getOptAccountName());
            //任务中断续传
            List<String> totalList = ArrayUtil.initList(gatherRecord.getTransitOrderIds().split(","));
            List<String> alreadyList = new ArrayList<>();
//            if (gatherRecord.getSureTransitOrderIds()!=null) {
//                alreadyList = ArrayUtil.initList(gatherRecord.getSureTransitOrderIds().split(","));
//            }
//            List<String> goingList = ArrayUtil.differenceList(totalList,alreadyList);
            //只查询未完成的数据
//            List<TransitOrder> goingGatherTransitOrderList = transitOrderMapper.selectBatchIds(goingList);
            List<TransitOrder> goingGatherTransitOrderList=new ArrayList<>();
            for (TransitOrder transitOrder : goingGatherTransitOrderList) {
                //当前订单号在总汇总订单号列表中的位置 ，所有的均摊费用要基于全部数据
                int orderIndex = totalList.indexOf(transitOrder.getId());
                transitOrder.setGatherTransportCost(MathUtil.average(gatherRecord.getGatherTotalTransportCost(), totalList.size(), orderIndex));
                transitOrder.setGatherTime(new Date());
                transitOrderMapper.updateById(transitOrder);
                //清算数据
                GoodsOrder goodsOrder = goodsOrderMapper.selectById(transitOrder.getGoodsOrderId());
                ClearingDetail clearingDetail = clearingService.getClearingDetailByTransitOrderId(transitOrder.getId());
                if (clearingDetail==null) clearingDetail = clearingService.createClearingDetail(transitOrder);
                clearingDetail.setActualSettlementType(GoodsOrder.SettlementType.gatherTotal);
                //设置费率
                clearingDetail.setShipperTaxRate(gatherRecord.getShipperTaxRate());
                clearingDetail.setInsuranceRate(gatherRecord.getInsuranceRate());
                clearingDetail.setShipperFeeRate(gatherRecord.getShipperFeeRate());
                clearingDetail.setTruckerFeeRate(gatherRecord.getTruckerFeeRate());
                clearingDetail.setAddedTaxRate(gatherRecord.getAddedTaxRate());
                clearingDetail.setCityTaxRate(gatherRecord.getCityTaxRate());
                clearingDetail.setLocalEduTaxRate(gatherRecord.getLocalEduTaxRate());
                clearingDetail.setIncomeTaxRate(gatherRecord.getIncomeTaxRate());
                clearingDetail.setEduAddTaxRate(gatherRecord.getEduAddTaxRate());
                //固定摊分费用 传入总 自动消除误差
                clearingDetail.setShipperTransportCost(MathUtil.average(gatherRecord.getGatherTotalTransportCost(), totalList.size(), orderIndex));
                clearingDetail.setAdditionalCost(MathUtil.average(gatherRecord.getGatherAdditionalCost(), totalList.size(), orderIndex));
                clearingDetail.setInsuranceCost(MathUtil.average(gatherRecord.getTotalInsuranceCost(), totalList.size(), orderIndex));
                clearingDetail.setDiffIndemnityCost(MathUtil.average(gatherRecord.getGatherDiffIndemnityCost(), totalList.size(), orderIndex));
                clearingDetail.setOilCost(MathUtil.average(gatherRecord.getGatherOilCost(), totalList.size(), orderIndex));
                clearingDetail.setEtcTollCost(MathUtil.average(gatherRecord.getGatherEtcTollCost(), totalList.size(), orderIndex));
                clearingDetail.setShipperFeeCost(MathUtil.average(gatherRecord.getGatherShipperFeeCost(), totalList.size(), orderIndex));
                clearingDetail.setShipperTaxCost(MathUtil.average(gatherRecord.getGatherShipperTaxCost(), totalList.size(), orderIndex));
                clearingDetail.setShipperActualPayCost(MathUtil.average(gatherRecord.getGatherActualPayCost(), totalList.size(), orderIndex));
                clearingDetail.setTruckerFeeCost(MathUtil.average(gatherRecord.getGatherTruckerFeeCost(), totalList.size(), orderIndex));
                clearingDetail.setAddedTaxCost(MathUtil.average(gatherRecord.getGatherAddedTaxCost(), totalList.size(), orderIndex));
                clearingDetail.setCityTaxCost(MathUtil.average(gatherRecord.getGatherCityTaxCost(), totalList.size(), orderIndex));
                clearingDetail.setLocalEduTaxCost(MathUtil.average(gatherRecord.getGatherLocalEduTaxCost(), totalList.size(), orderIndex));
                clearingDetail.setEduAddTaxCost(MathUtil.average(gatherRecord.getGatherEduAddTaxCost(), totalList.size(), orderIndex));
                clearingDetail.setIncomeTaxCost(MathUtil.average(gatherRecord.getGatherIncomeTaxCost(), totalList.size(), orderIndex));
                clearingDetail.setTruckerTaxCost(MathUtil.average(gatherRecord.getGatherTruckerTaxCost(), totalList.size(), orderIndex));
                clearingDetail.setTruckerActualTheoryCost(MathUtil.average(gatherRecord.getGatherTruckerTheoryCost(), totalList.size(), orderIndex));
                clearingDetail.setTechnicalFeeCost(MathUtil.average(gatherRecord.getGatherTechnicalFeeCost(), totalList.size(), orderIndex));
                clearingDetail.setTruckerActualIncomeCost(MathUtil.average(gatherRecord.getGatherTruckerIncomeCost(), totalList.size(),orderIndex));
                //锁定用户
                clearingDetail.setOptAccountId(loginUser.getId());
                clearingDetail.setOptAccountName(loginUser.getName());
                clearingDetail.setLockTime(new Date());
                clearingDetail.setGatherRecordId(gatherRecord.getId());
                clearingDetail.setGatherRecordNo(gatherRecord.getGatherRecordNo());
                //设置详细的清算费用 后直接保存
                clearingService.updateById(clearingDetail);
                //自动确认清算
                if (gatherRecord.getAutoSureClearing()){
                    clearingService.sureClearingDetail(loginUser,transitOrder,clearingDetail);
                }
                alreadyList.add(transitOrder.getId());
//                gatherRecord.setSureTransitOrderIds(String.join(",",alreadyList));
                gatherRecordMapper.updateById(gatherRecord);
            }
            gatherRecord.setGatherStatus(GatherRecord.GatherStatus.confirmed);
            gatherRecord.setConfirmTime(new Date());
            gatherRecordMapper.updateById(gatherRecord);
        }
    }

    /**
     * 找查：订单号获取清汇总单
     * 对应订单所在的汇总单
     */
    public GatherRecord getGatherRecordByTransitOrderId(String transitOrderId) {
        QueryWrapper<GatherRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("transit_order_ids", transitOrderId);
        List<Integer> statusIndexList = ArrayUtil.initList(GatherRecord.GatherStatus.create.index, GatherRecord.GatherStatus.confirmed.index, GatherRecord.GatherStatus.deal.index);
        queryWrapper.in("gather_status", statusIndexList);
        return gatherRecordMapper.selectOne(queryWrapper);
    }

    /**
     * 找查：等待清算汇总单
     */
    public List<GatherRecord> getAutoClearingGather() {
        QueryWrapper<GatherRecord> queryWrapper = new QueryWrapper<>();
        List<Integer> statusIndexList = ArrayUtil.initList(GatherRecord.GatherStatus.deal.index);
        queryWrapper.in("gather_status", statusIndexList);
        return gatherRecordMapper.selectList(queryWrapper);
    }


    //###检查汇总数据
    private void checkGatherRecord(TransitOrder firstOrder, List<TransitOrder> transitOrderList) {
        transitOrderList.forEach(transitOrder -> {
            if (transitOrder.getTransitStatus() != TransitOrder.TransitStatus.waitingSettlement) {
                throw new BusinessException(String.format("运单:%s 不在清算状态,不能汇总!", transitOrder.getTransportNo()));
            }
            if (transitOrder.getSettlementType() != GoodsOrder.SettlementType.gatherTotal) {
                throw new BusinessException(String.format("运单:%s 不需要汇总结算,不能汇总!", transitOrder.getTransportNo()));
            }
            if (!transitOrder.getShipperOrganizeId().equals(firstOrder.getShipperOrganizeId())) {
                throw new BusinessException(String.format("运单:%s 货主信息不一致,不能汇总!", transitOrder.getTransportNo()));
            }
            if (!transitOrder.getRobOrganizeId().equals(firstOrder.getRobOrganizeId())) {
                throw new BusinessException(String.format("运单:%s 车主信息不一致,不能汇总!", transitOrder.getTransportNo()));
            }
            GatherRecord gatherRecord = getGatherRecordByTransitOrderId(transitOrder.getId());
            if (gatherRecord != null) {
                throw new BusinessException(String.format("运单:%s 已存在汇总记录:%s,请移除该条运单或作废源记录!", transitOrder.getTransportNo(), gatherRecord.getGatherRecordNo()));
            }
        });
    }

}












